package com.zmj.mobile.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmj.framework.base.service.impl.BaseServiceImpl;
import com.zmj.mobile.entity.OrgEntity;
import com.zmj.mobile.entity.OrgUserEntity;
import com.zmj.mobile.entity.UserEntity;
import com.zmj.mobile.mapper.IOrgMapper;
import com.zmj.mobile.service.IOrgService;
import com.zmj.mobile.service.IOrgUserService;
import com.zmj.mobile.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * <p>

 * </p>
 *
 * @author lzy
 * @since 2024-02-01
 */
@Service
public class OrgServiceImpl extends BaseServiceImpl<IOrgMapper, OrgEntity> implements IOrgService {

    @Resource
    private IOrgUserService iOrgUserService;

    @Resource
    private IUserService iUserService;

    @Override
    public List<OrgEntity> getListByParentId(String parentId) {

        LambdaQueryWrapper<OrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrgEntity::getParentOrgCode, parentId);
        queryWrapper.eq(OrgEntity::getIsDeleted, 0);

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public OrgEntity getOneByCode(String orgCode) {

        LambdaQueryWrapper<OrgEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrgEntity::getOrgCode, orgCode);
        queryWrapper.eq(OrgEntity::getIsDeleted, 0);
        queryWrapper.last("limit 1");

        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public OrgEntity getById(Integer id) {

        return baseMapper.selectById(id);
    }

    @Override
    public Optional<OrgEntity> getByUserName(String userName) {

        if (StringUtils.isBlank(userName)) {
            return Optional.empty();
        }

        UserEntity userEntity = iUserService.getOneByName(userName);

        if (Objects.isNull(userEntity)) {
            return Optional.empty();
        }

        OrgUserEntity orgUserEntity = iOrgUserService.getOrgIdByUserId(userEntity.getId());

        if (Objects.isNull(orgUserEntity)) {
            return Optional.empty();
        }

        return Optional.ofNullable(baseMapper.selectById(orgUserEntity.getOrgId()));
    }
}
